package com.cloudkinto.service.covershows.impl;

import com.cloudkinto.common.constant.GlobalConstants;
import com.cloudkinto.entity.NewsInformationDo;
import com.cloudkinto.dao.NewsInformationDao;
import com.cloudkinto.service.covershows.NewsInformationService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.cloudkinto.common.web.PageResult;
import com.cloudkinto.common.web.SingleResult;

import com.cloudkinto.service.covershows.vo.NewsInformationAddReq;
import com.cloudkinto.service.covershows.vo.NewsInformationDetailRes;
import com.cloudkinto.service.covershows.vo.NewsInformationPageRes;
import com.cloudkinto.service.covershows.vo.NewsInformationUpdateReq;
import com.cloudkinto.service.file.FileService;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.util.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * <p>
 *  service实现类
 * </p>
 * @author zhangyy
 * @since 2020-09-27
 */
@Service
@Transactional(rollbackFor = Exception.class)//事务回滚
public class NewsInformationServiceImpl extends ServiceImpl<NewsInformationDao, NewsInformationDo> implements NewsInformationService {
    @Autowired
    private NewsInformationDao dao;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private FileService fileService;

    @Override
    public SingleResult addInit() {
        return SingleResult.success("");
    }

    @Override
    public void add(NewsInformationAddReq req, Long userId) {
        NewsInformationDo entityDo = new NewsInformationDo();
        BeanUtils.copyProperties(req, entityDo);
        entityDo.setBrowseCount(10000);
        entityDo.setCollectCount(10000);
        handlerAddBefore(entityDo, userId);
        dao.insert(entityDo);

        fileService.uploadFile(req.getFileId());
    }

    //新增校验
    private void addCheck(Object req) {

    }

    //做新增之前要执行的业务定制处理
    private void handlerAddBefore(NewsInformationDo entityDo, Long userId) {
        entityDo.setCreateTime(new Date());
    }

    //将新增的do转换成要返回的实体
    private Object handlerAddAfter(NewsInformationDo entityDo) {
        Object res = new Object();
        BeanUtils.copyProperties(entityDo, res);
        return res;
    }

    @Override
    public SingleResult updateInit(Long id) {
        return SingleResult.success(detail(id));
    }

    @Override
    public void update(NewsInformationUpdateReq req, Long userId) {
        NewsInformationDo entityDo = dao.selectById(req.getId());
        if(req.getFileId() != null){
            fileService.deleteFile(entityDo.getFileId());
            fileService.uploadFile2(req.getFileId(),entityDo.getFileId());
        }

        BeanUtils.copyProperties(req, entityDo);
        handlerUpdateBefore(entityDo, userId);
        dao.updateById(entityDo);
    }

    //编辑校验
    private void updateCheck(Object req) {

    }

    //做修改之前要执行的业务定制处理
    private void handlerUpdateBefore(NewsInformationDo entityDo, Long userId) {
    }

    //做修改之后要执行的业务定制处理
    private Object handlerUpdateAfter(NewsInformationDo entityDo) {
        Object res = new Object();
        BeanUtils.copyProperties(entityDo, res);
        return res;
    }

    @Override
    public int delete(Long id, Long userId) {
        return dao.deleteById(id);
    }


    @Override
    public NewsInformationDetailRes detail(Long id) {
        NewsInformationDo entityDo =  dao.selectById(id);
        entityDo.setBrowseCount(entityDo.getBrowseCount() + 1);
        entityDo.setCollectCount(entityDo.getCollectCount() + 1);
        dao.updateById(entityDo);
        NewsInformationDetailRes res = new NewsInformationDetailRes();
        BeanUtils.copyProperties(entityDo, res);
        res.setFileUrl(fileService.getFilePath(entityDo.getFileId()));
        return res;
    }

    //查询明细之后要执行的业务定制处理
    private Object handlerDetailAfter(Object res) {
        return res;
    }

    @Override
    public SingleResult pageInit() {
        return SingleResult.success("");
    }

    @Override
    public List<NewsInformationPageRes> getList(Map<String, String> map) {
        QueryWrapper<NewsInformationDo> wrapper = queryBuild(map);
        List<NewsInformationDo> list = this.list(wrapper);
        List<NewsInformationPageRes> result = handlerListAfter(list);
        return result;
    }

    @Override
    public PageResult getListPage(Map<String, String> map) {
        QueryWrapper<NewsInformationDo> wrapper = queryBuild(map);
        IPage<NewsInformationDo> page = pageInit(map);
        page = this.page(page, wrapper);
        List<NewsInformationPageRes> resList = handlerListAfter(page.getRecords());
        PageResult result = new PageResult(resList, (int)page.getCurrent(), (int)page.getSize(), (int)page.getTotal(), (int)page.getPages());
        return result;
    }

    @Override
    public SingleResult dataStatistics() {
        Integer fbaInputCount = (Integer) redisTemplate.opsForValue().get(GlobalConstants.FBA_INPUT_KEY);
        Integer jpSendOutCount = (Integer) redisTemplate.opsForValue().get(GlobalConstants.JP_SEND_OUT_KEY);
        Integer orderBackOutCount = (Integer) redisTemplate.opsForValue().get(GlobalConstants.ORDER_BACK_KEY);
        Integer storageAreaCount = (Integer) redisTemplate.opsForValue().get(GlobalConstants.STORAGE_AREA_KEY);

        if(fbaInputCount == null){
            fbaInputCount = 0;
        }
        if(jpSendOutCount == null){
            jpSendOutCount = 0;
        }
        if(orderBackOutCount == null){
            orderBackOutCount = 0;
        }
        if(storageAreaCount == null){
            storageAreaCount = 0;
        }

        Map map = new HashMap();
        map.put("fbaInputCount",fbaInputCount);
        map.put("jpSendOutCount",jpSendOutCount);
        map.put("orderBackOutCount",orderBackOutCount);
        map.put("storageAreaCount",storageAreaCount);
        return SingleResult.success(map);
    }

    //查询分页列表之后对列表数据的处理
    private List<NewsInformationPageRes> handlerListAfter(List<NewsInformationDo> list ){
        List<NewsInformationPageRes> result = new ArrayList<>();
        if(!CollectionUtils.isEmpty(list)){
            list.forEach(newsInformationDo -> {
                NewsInformationPageRes res = new NewsInformationPageRes();
                BeanUtils.copyProperties(newsInformationDo, res);
                res.setFileUrl(fileService.getFilePath(newsInformationDo.getFileId()));
                result.add(res);
            });
        }
        return result;
    }

    private IPage<NewsInformationDo> pageInit(Map<String, String> map) {
        IPage<NewsInformationDo> page = new Page();
        page.setSize(StringUtils.isNotBlank(map.get("pageSize")) ? Long.parseLong(map.get("pageSize")) : 10);
        page.setCurrent(StringUtils.isNotBlank(map.get("current")) ? Long.parseLong(map.get("current")) : 1);
        return page;
    }

    private QueryWrapper<NewsInformationDo> queryBuild(Map<String, String> map) {
        QueryWrapper<NewsInformationDo> wrapper = new QueryWrapper<>();
//        if (StringUtils.isNotBlank(map.get("keyword"))) {
//            wrapper.like("keyword", map.get("keyword"));
//        }
        return wrapper.orderByDesc("id");
    }


}
